// Promise 自定义实现 
import request from "./request"

class Mypromise {
    constructor (fn) {
        this.status = "pendding"
        this.value = undefined
        // then可以被同一个实例多次调用
        this.successCallback = []
        this.failCallback = []

        fn(this.resolve, this.reject)
    }

    resolve = (value) => {
        if(this.status !== "pendding"){
            return 
        }
        this.status = "success"
        this.value = value

        while(this.successCallback.length > 0){
            this.successCallback.shift()(value)
        }
    }

    reject = (error) => {
        if(this.status !== "pendding"){
            return 
        }
        this.status = "fail"
        this.value = error

        while(this.failCallback.length > 0){
            this.failCallback.shift()(error)
        }
    }

    then (successCallback, failCallback) {
        let promise2 = new Mypromise((resolve, reject) => {

            // 同步场景
            if(this.status === "success"){
                let x = successCallback && successCallback(this.value)
                this.resolveValue(x, resolve, reject)
            }

            if(this.status === "fail"){
                let x = failCallback && failCallback(this.error)
                this.resolveValue(x, resolve, reject)
            }

            // 异步场景
            if(this.status === "pendding"){
                this.successCallback.push(() => {
                    let x = successCallback && successCallback(this.value)
                    this.resolveValue(x, resolve, reject)
                })
                this.failCallback.push(() => {
                    let x = failCallback && failCallback(this.value)
                    this.resolveValue(x, resolve, reject)
                })
            }
        })

        return promise2
    }


    resolveValue(x, resolve, reject){
        if(x instanceof Mypromise){
            x.then(resolve, reject)
        }
        else{
            resolve(x)
        }
    }
}

// 基本使用
const p = new Mypromise((resolve, reject) => {
    setTimeout(() => {
        resolve("data 100")
    }, 1000);

})

p.then(data => {
    console.log("setTimeout:", data)

    return new Mypromise((resolve, reject)=>{
        request({
            url: "http://192.168.199.187:1337/blogs"
        }).then(resolve, reject)
    })
})
.then(data => {
    console.log("request:", data)

}, error => {

})


// 并行发送，限制并行数



export default Mypromise